<?php

/**
 * ContactForm class.
 * ContactForm is the data structure for keeping
 * contact form data. It is used by the 'contact' action of 'SiteController'.
 */
class RegisterForm extends CFormModel
{
	public $username;
	public $realname;
	public $email;
	public $password;
	public $password2;
	public $verifyCode;

	/**
	 * Declares the validation rules.
	 */
	public function rules()
	{
		return array(
			// name, email, subject and body are required
			array('username, realname, email, password, password2', 'required'),
			// email y username deben ser unicos
			array('username', 'unique_username'),
			array('email', 'unique_email'),
			// email has to be a valid email address
			array('email', 'email'),
                        // verificar que coincidan las contraseñas
			array('password2', 'compare', 'compareAttribute'=>'password'),
			// verifyCode needs to be entered correctly
			array('verifyCode', 'captcha', 'allowEmpty'=>!extension_loaded('gd')),
		);
	}

	/**
	 * Declares customized attribute labels.
	 * If not declared here, an attribute would have a label that is
	 * the same as its name with the first letter in upper case.
	 */
	public function attributeLabels()
	{
		return array(
			'username'=>'usuario',
			'realname'=>'nombre real',
			'email'=>'email',
			'password'=>'contraseña',
			'password2'=>'repite contraseña',
			'verifyCode'=>'código de verificación',
		);
	}

        public function addUser() {
          $user = new User();
          $user->username=$this->username;
          $user->realname=$this->realname;
          $user->email=$this->email;
          $user->password=md5($this->password);
          $user->save();
        }

        public function unique_username() {
          $user = User::model()->find("username='{$this->username}'");
          if ($user!=null)
            $this->addError('username', "el usuario introducido (<strong>{$this->username}</strong>) ya existe en la base de datos");
        }
        public function unique_email() {
          $user = User::model()->find("email='{$this->email}'");
          if ($user!=null)
            $this->addError('username', "el email introducido (<strong>{$this->email}</strong>) ya existe en la base de datos");
        }
}